package com.bot.backend.service.impl.user.snake;

import com.bot.backend.mapper.SnakeMapper;
import com.bot.backend.pojo.Snake;
import com.bot.backend.pojo.User;
import com.bot.backend.service.impl.utils.UserDetailsImpl;
import com.bot.backend.service.user.snake.RemoveSnakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class removeSnakeServiceImpl implements RemoveSnakeService {
    @Autowired
    private SnakeMapper botMapper;

    @Override
    public Map<String, String> removeSnake(Map<String, String> data) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) usernamePasswordAuthenticationToken.getPrincipal();

        User user = loginUser.getUser();
        int snake_id = Integer.parseInt(data.get("snake_id"));
        Snake selectById = botMapper.selectById(snake_id);

        Map<String, String> map = new HashMap<>();

        if (selectById == null) {
            map.put("error_massage", "您的snake不存在");
            return map;
        }

        if (!selectById.getUserId().equals(user.getId())) {
            map.put("error_message", "您没有权限删除该snake");
            return map;
        }

        int deleteById = botMapper.deleteById(snake_id);
        if (deleteById > 0) map.put("error_message", "success");

        return map;
    }
}
